import * as httpConfig from './config'
import * as mutationsTypes from '@/store/mutationsTypes'
import { storage } from '@/utils/storage'
const http = uni.$u.http

import store from '@/store'

const manageCode = data => {
  if (data.status === '0') return data
  switch (data.code) {
    // 200放行
    case 200:
      return data
    // token失效或者无权限
    case 401:
      return data
    // 用户被冻结
    case 505:
      return data
    default:
      return data
  }
}

export default () => {
  // 初始化请求配置
  http.setConfig(config => {
    /* config 为默认全局配置*/
    config.baseURL = httpConfig.BASE_URL /* 根域名 */
    config.timeout = httpConfig.TIME_OUT
    return config
  })

  // 请求拦截
  http.interceptors.request.use(
    config => {
      // 修改加载的状态
      const token = storage.getItem('token')
      store.commit(mutationsTypes.CHANGE_LOADING_STATE, true)
      config.header = {
        'API-Authorization': token || '',
        ...config.header
      }
      // 演示custom 用处
      // if (config.custom.auth) {
      //   config.header.token = 'token'
      // }
      // if (config.custom.loading) {
      //  uni.showLoading()
      // }
      // 演示
      // if (!token) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
      // 	return Promise.reject(config)
      // }
      return config
    },
    config => {
      // 可使用async await 做异步操作
      return Promise.reject(config)
    }
  )

  // 响应拦截
  http.interceptors.response.use(
    response => {
      store.commit(mutationsTypes.CHANGE_LOADING_STATE, false)
      const data = response.data

      /* 对响应成功做点什么 可使用async await 做异步操作*/
      const responseData = manageCode(data)
      return responseData
    },
    response => {
      /*  对响应错误做点什么 （statusCode !== 200）*/
      store.commit(mutationsTypes.CHANGE_LOADING_STATE, false)
      return Promise.reject(response)
    }
  )
}

/**
uni.$u.http.get(url[, config])
uni.$u.http.upload(url[, config])
uni.$u.http.delete(url[, data[, config]])
uni.$u.http.head(url[, data[, config]])
uni.$u.http.post(url[, data[, config]])
uni.$u.http.put(url[, data[, config]])
uni.$u.http.connect(url[, data[, config]])
uni.$u.http.options(url[, data[, config]])
uni.$u.http.trace(url[, data[, config]])
*/

// 对request进行再次封装  使得请求跟axios一样
const request = config => {
  let { url, method = 'get', data = {}, params = {}, ...arg } = config
  method = method.toLowerCase()

  switch (method) {
    case 'get':
    case 'upload':
      return http[method](url, { params, ...arg })
    default:
      return http[method](url, data, { params, ...arg })
  }
}

export { request }
